package bai4.com.server;
/**
 * @author nglehien
 * Oct 21, 2012 - 8:44:26 PM
 */
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class ServerGUI extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1102207982054134791L;
	private JPanel contentPane;
	private JLabel lblServerState;
	ServerSocket serverSocket;
	private Socket socket = new Socket();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ServerGUI frame = new ServerGUI();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ServerGUI() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 479, 149);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		lblServerState = new JLabel("State:");
		lblServerState.setFont(new Font("Times New Roman", Font.PLAIN, 35));
		lblServerState.setBounds(10, 11, 443, 41);
		contentPane.add(lblServerState);

		JButton btnStartServer = new JButton("Start Server");
		btnStartServer.addActionListener(onClickStartServer);
		btnStartServer.setFont(new Font("Times New Roman", Font.PLAIN, 20));
		btnStartServer.setBounds(163, 63, 141, 37);
		contentPane.add(btnStartServer);
	}



	private ActionListener onClickStartServer = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			try {
				serverSocket = new ServerSocket(9999);
				lblServerState.setText("Server is ready");
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						while (true) {
							try {
								socket = serverSocket.accept();
								new MyConnection(socket);
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					}
				});
				thread.start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
}
